from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from rest_framework import status
from drf_template_admin import settings
from drf_template_admin.enums import expire
import jwt, datetime

class JWT(BaseAuthentication):
    # 生成Token
    def generate_token(self, id, username):
        secret = settings.dev.SECRET_KEY
        headers = {'typ': 'jwt', 'alg': 'HS256'}
        payload = {'id': id, 'username': username, 'exp': datetime.datetime.utcnow()  + datetime.timedelta(seconds=expire.BACKEND_EXPIRE)}
        return jwt.encode(payload=payload, key=secret, algorithm='HS256', headers=headers)
    
    # 校验token
    def authenticate(self, request):
        token = request.META.get('HTTP_AUTHORIZATION')[7:]
        if not token:
            raise AuthenticationFailed({"status": status.HTTP_401_UNAUTHORIZED,"errorCode": "40001", "errorMessage": "Token不存在"})
        
        secret = settings.dev.SECRET_KEY
        try:
            jwt.decode(token, secret, algorithms='HS256')
            return '', token, 
        except jwt.ExpiredSignatureError:
            raise AuthenticationFailed({"status": status.HTTP_401_UNAUTHORIZED,"errorCode": "40002", "errorMessage": "Token 已过期"})
        
        except jwt.DecodeError:
            raise AuthenticationFailed({"status": status.HTTP_401_UNAUTHORIZED,"errorCode": "40003", "errorMessage": "Token 认证失败"})

        except jwt.InvalidTokenError:
            raise AuthenticationFailed({"status": status.HTTP_401_UNAUTHORIZED,"errorCode": "40004", "errorMessage": "非法Token"})
        
    def authenticate_header(self, request):
        return 'token'    